package com.forlove.app.qselect.answer.widght.indicator;

import android.content.Context;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.forlove.app.R;
import com.nineoldandroids.view.ViewHelper;

import static android.support.v4.view.ViewPager.SCROLL_STATE_IDLE;
import static android.support.v4.view.ViewPager.SCROLL_STATE_SETTLING;

/**
 * Created by yjl on 2017/12/4.
 */

public class TitleTabIndicator extends FrameLayout implements ViewPager.OnPageChangeListener {
    private Context mContext;
    private RelativeLayout mTabs;
    private View line_indicator;
    private ViewPager mViewPager;
    //    private TitleBarViewPager mViewPager;
    private ViewPager.OnPageChangeListener mListener;
    private int mScrollState;
    private int mPreviousScrollState = mScrollState;
    private int mCurrentPage;
    private float mPositionOffset;
    private int selectPosition = mCurrentPage;//确定到选中的页面

    public TitleTabIndicator(@NonNull Context context) {
        super(context);
        init(context);
    }

    /**
     * 控件构造。
     *
     * @param context 上下文
     * @param attrs   参数
     */
    public TitleTabIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TitleTabIndicator(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context) {
        mContext = context;
        View.inflate(context, R.layout.widget_titletab_indicator, this);
        mTabs = (RelativeLayout) findViewById(R.id.rl_tabs);
        for (int i = 0, count = mTabs.getChildCount(); i < count; i++) {
            final int index = i;
            View view = mTabs.getChildAt(index);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    setCurrentItem(index);
                }
            });
        }
        line_indicator = findViewById(R.id.line_indicator);

    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            final boolean updateIndicator = mScrollState == SCROLL_STATE_IDLE ||
                    (mScrollState == SCROLL_STATE_SETTLING && mPreviousScrollState == SCROLL_STATE_IDLE);
            refresh(updateIndicator);
        }
    }

    /**
     * 设置与当前TabView对应的ViewPager。
     *
     * @param viewPager 对应的ViewPager。
     */

    public void setViewPager(ViewPager viewPager) {
        if (mViewPager == viewPager) {
            return;
        }
        if (mViewPager != null) {
            mViewPager.setOnPageChangeListener(null);
        }

        if (viewPager.getAdapter() == null) {
            throw new IllegalStateException(
                    "ViewPager does not have adapter instance.");
        }

        if (viewPager.getAdapter().getCount() != mTabs.getChildCount()) {
            throw new IllegalStateException(
                    "ViewPager does not have adapter instance.");
        }
        mViewPager = viewPager;
        mViewPager.setOnPageChangeListener(this);
        final boolean updateIndicator = mScrollState == SCROLL_STATE_IDLE
                || (mScrollState == SCROLL_STATE_SETTLING && mPreviousScrollState == SCROLL_STATE_IDLE);
        refresh(updateIndicator);
    }

    /**
     * 设置与当前TabView对应的ViewPager,同事设置初始位置.
     *
     * @param viewPager       对应的ViewPager。
     * @param initialPosition 初始位置
     */

    public void setViewPager(ViewPager viewPager, int initialPosition) {
        setViewPager(viewPager);
        setCurrentItem(initialPosition);
    }

    /**
     * 设置当前ViewPager和Tab对应的位置.
     *
     * @param item 对应的位置。
     */

    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            throw new IllegalStateException("ViewPager has not been bound.");
        }
        mViewPager.setCurrentItem(item);
//        mCurrentPage = item;
//        refresh();//导致每次点击的时候会有闪的效果
    }

    // 0 不 1中 2完毕
    @Override
    public void onPageScrollStateChanged(int state) {
//        LogUtil.e("yjl", "onPageScrollStateChanged  state:" + state);
        mPreviousScrollState = mScrollState;
        mScrollState = state;
        if (mListener != null) {
            mListener.onPageScrollStateChanged(state);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        mCurrentPage = position;
        if (positionOffset < 1) {
            mPositionOffset = positionOffset;
        }
        final boolean updateIndicator = !(mScrollState == SCROLL_STATE_SETTLING && mPreviousScrollState == SCROLL_STATE_IDLE);
        refresh(updateIndicator);

        if (mListener != null) {
            mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }
    }

    @Override
    public void onPageSelected(int position) {
        if (mTabs != null && position < mTabs.getChildCount()) {
            mCurrentPage = position;
            selectPosition = position;
            final boolean updateIndicator = mScrollState == SCROLL_STATE_IDLE ||
                    (mScrollState == SCROLL_STATE_SETTLING && mPreviousScrollState == SCROLL_STATE_IDLE);
            refresh(updateIndicator);
            if (mListener != null) {
                mListener.onPageSelected(position);
            }
        }
    }

    /**
     * 监听Tab及ViewPager变化。
     *
     * @param listener 用于监听的Listener.
     */

    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mListener = listener;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        mCurrentPage = savedState.mCurrentPage;
        selectPosition = savedState.mCurrentPage;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.mCurrentPage = selectPosition;
        return savedState;
    }

    public void refresh(final boolean updateIndicator) {
        int roundedPosition = Math.round(mCurrentPage + mPositionOffset);
        if (roundedPosition < 0 || roundedPosition >= mTabs.getChildCount()) {
            return;
        }


        int lineX = (line_indicator.getRight() - line_indicator.getLeft()) / 2;

        View leftView = mTabs.getChildAt(mCurrentPage);
        View rightView = mTabs.getChildAt(mCurrentPage + 1);
        int leftCenter = 0;
        if (leftView != null) {
            leftCenter = (leftView.getLeft() + leftView.getRight()) / 2;
        }
        int rightCenter = 0;

        if (rightView != null) {
            rightCenter = (rightView.getLeft() + rightView.getRight()) / 2;
        }
        int indicatorCenter = (int) (leftCenter + (rightCenter) * mPositionOffset);

        //左边中间位置
//        ViewHelper.setTranslationX(line_indicator, mTabs.getLeft() + leftCenter - lineX);
        //右边中间位置
//        ViewHelper.setTranslationX(line_indicator, mTabs.getLeft() + rightCenter - lineX);

        float alphaLeft = (float) (1 - (indicatorCenter - leftCenter) * 1.0f
                / (rightCenter - leftCenter) * 0.4);
        float scaleLeft = (float) (1 - (indicatorCenter - leftCenter) * 1.0f
                / (rightCenter - leftCenter) * 0.02);
        float alphaRight = (float) (0.6 + (indicatorCenter - leftCenter) * 1.0f
                / (rightCenter - leftCenter) * 0.4);
        float scaleRight = (float) (0.98 + (indicatorCenter - leftCenter)
                * 1.0f / (rightCenter - leftCenter) * 0.02);

        if (updateIndicator) {
            int width = (int) ((rightCenter - leftCenter) * mPositionOffset);
            int dex = mTabs.getLeft() + (leftCenter - lineX) + width;
            ViewHelper.setTranslationX(line_indicator, dex);
        }
        for (int i = 0, count = mTabs.getChildCount(); i < count; i++) {
            final int index = i;
            View view = mTabs.getChildAt(index);
            if (i == selectPosition) {
                ((TextView) view).setTextColor(mContext.getResources().getColor(R.color.common_green));
            } else {
                ((TextView) view).setTextColor(mContext.getResources().getColor(R.color.str_color_sub_gray));
            }
            if (view == leftView) {
                ViewHelper.setAlpha(view, alphaLeft);
                ViewHelper.setScaleX(view, scaleLeft);
                ViewHelper.setScaleY(view, scaleLeft);
            } else if (view == rightView) {
                ViewHelper.setAlpha(view, alphaRight);
                ViewHelper.setScaleX(view, scaleRight);
                ViewHelper.setScaleY(view, scaleRight);
            } else {
                ViewHelper.setAlpha(view, 0.6f);
                if (Float.isNaN(ViewHelper.getScaleX(view))
                        || Float.isNaN(ViewHelper.getScaleY(view))) {
                    ViewHelper.setScaleX(view, scaleRight);
                    ViewHelper.setScaleY(view, scaleRight);
                }
            }
        }

    }
}
